package com.mdp.arc.archive.ctrl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.mdp.arc.archive.entity.Archive;
import com.mdp.arc.archive.entity.ArchiveUp;
import com.mdp.arc.archive.service.ArchiveCalcService;
import com.mdp.arc.archive.service.ArchiveService;
import com.mdp.arc.archive.service.ArchiveUpService;
import com.mdp.core.api.CacheHKVService;
import com.mdp.core.entity.Result;
import com.mdp.core.err.BizException;
import com.mdp.core.query.QueryTools;
import com.mdp.msg.client.PushNotifyMsgService;
import com.mdp.safe.client.entity.User;
import com.mdp.safe.client.utils.LoginUtils;
import com.mdp.swagger.ApiEntityParams;
import io.swagger.annotations.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.util.Date;
import java.util.List;
import java.util.Map;

import static com.mdp.core.utils.BaseUtils.toMap;

/**
 * url编制采用rest风格,如对arc_archive_up 文章点赞人员列表的操作有增删改查,对应的url分别为:<br>
 * 组织 com.mdp  顶级模块 arc 大模块 archive 小模块 <br>
 * 实体 ArchiveUp 表 arc_archive_up 当前主键(包括多主键): archive_id,userid; 
 ***/
@RestController("arc.archive.archiveUpController")
@RequestMapping(value="/*/arc/archive/archiveUp")
@Api(tags={"文章点赞人员列表操作接口"})
public class ArchiveUpController {
	
	static Logger logger =LoggerFactory.getLogger(ArchiveUpController.class);
	
	@Autowired
	private ArchiveUpService archiveUpService;

	@Autowired
	private ArchiveService archiveService;

	@Autowired
	PushNotifyMsgService pushNotifyMsgService;

	@Autowired
	CacheHKVService cacheHKVService;

	Map<String,Object> fieldsMap = toMap(new ArchiveUp());
 
	
	@ApiOperation( value = "查询文章点赞人员列表信息列表",notes=" ")
	@ApiEntityParams( ArchiveUp.class )
	@ApiImplicitParams({
			@ApiImplicitParam(name="pageSize",value="每页大小，默认20条",required=false),
			@ApiImplicitParam(name="pageNum",value="当前页码,从1开始",required=false),
			@ApiImplicitParam(name="total",value="总记录数,服务器端收到0时，会自动计算总记录数，如果上传>0的不自动计算",required=false),
			@ApiImplicitParam(name="count",value="是否计算总记录条数，如果count=true,则计算计算总条数，如果count=false 则不计算",required=false),
			@ApiImplicitParam(name="orderBy",value="排序列 如性别、学生编号排序 orderBy = sex desc,student desc",required=false),
 	})
	@ApiResponses({
		@ApiResponse(code = 200,response=ArchiveUp.class,message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'错误码'},total:总记录数,data:[数据对象1,数据对象2,...]}")
	})
	@RequestMapping(value="/list",method=RequestMethod.GET)
	public Result listArchiveUp(@ApiIgnore @RequestParam Map<String,Object> params ){
		
		
		IPage page= QueryTools.initPage(params);
		List<Map<String,Object>>	datas = archiveUpService.selectListMapByWhere(page,QueryTools.initQueryWrapper(ArchiveUp.class,params),params);	//列出ArchiveUp列表
		
		return Result.ok().setData(datas);
	}
	
 

	@ApiOperation( value = "新增一条文章点赞人员列表信息",notes=" ")
	@ApiResponses({
		@ApiResponse(code = 200,response=ArchiveUp.class,message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'},data:数据对象}")
	}) 
	@RequestMapping(value="/add",method=RequestMethod.POST)
	public Result addArchiveUp(@RequestBody ArchiveUp archiveUp) {
		
		
		try{
			if(!StringUtils.hasText(archiveUp.getArchiveId())){
				return Result.error("archiveId-0","文章编号不能为空");
			}
		    User user=LoginUtils.getCurrentUserInfo();
		    archiveUp.setUserid(user.getUserid());
			if(archiveUpService.selectOneObject(archiveUp) !=null ){
				return Result.error("pk-exists","已点赞");
			}
			archiveUp.setUtime(new Date());
			archiveUpService.insert(archiveUp);
			ArchiveCalcService.upSet.add(archiveUp.getArchiveId());
			Archive archiveDb=archiveService.selectOneById(archiveUp.getArchiveId());
			if(!user.getUserid().equals(archiveDb.getUserid())) {
				pushNotifyMsgService.pushMsg(user, archiveDb.getUserid(), archiveDb.getAuthorName(), user.getUsername() + "点赞了文章：" + archiveDb.getArchiveTitle(),null);
			}
			return Result.ok().setData(archiveUp);
		}catch (BizException e) {
			logger.error("",e);
			return Result.error(e);
		}catch (Exception e) {
			logger.error("",e);
			return Result.error(e.getMessage());

		}
	}

	@ApiOperation( value = "删除一条文章点赞人员列表信息",notes=" ")
	@ApiResponses({
		@ApiResponse(code = 200, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'}}")
	}) 
	@RequestMapping(value="/del",method=RequestMethod.POST)
	public Result delArchiveUp(@RequestBody ArchiveUp archiveUp){
		
		
		try{
            if(!StringUtils.hasText(archiveUp.getArchiveId())) {
                 return Result.error("pk-not-exists","请上送主键参数archiveId");
            }
			User user=LoginUtils.getCurrentUserInfo();
			archiveUp.setUserid(user.getUserid());
            ArchiveUp archiveUpDb = archiveUpService.selectOneObject(archiveUp);
            if( archiveUpDb == null ){
                return Result.error("data-not-exists","已取消点赞");
            }
			archiveUpService.deleteByPk(archiveUp);
		}catch (BizException e) {
		logger.error("",e);
		return Result.error(e);
	}catch (Exception e) {
		logger.error("",e);
		return Result.error(e.getMessage());

	}  
		return Result.ok();
	}
	
	/**
	@ApiOperation( value = "根据主键修改一条文章点赞人员列表信息",notes=" ")
	@ApiResponses({
		@ApiResponse(code = 200,response=ArchiveUp.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'},data:数据对象}")
	}) 
	@RequestMapping(value="/edit",method=RequestMethod.POST)
	public Result editArchiveUp(@RequestBody ArchiveUp archiveUp) {
		
		
		try{
            if(!StringUtils.hasText(archiveUp.getArchiveId())) {
                 return failed("pk-not-exists","请上送主键参数archiveId");
            }
            if(!StringUtils.hasText(archiveUp.getUserid())) {
                 return failed("pk-not-exists","请上送主键参数userid");
            }
            ArchiveUp archiveUpDb = archiveUpService.selectOneObject(archiveUp);
            if( archiveUpDb == null ){
                return failed("data-not-exists","数据不存在，无法修改");
            }
			archiveUpService.updateSomeFieldByPk(archiveUp);
			return Result.ok().setData(archiveUp);
		}catch (BizException e) {
		logger.error("",e);
		return Result.error(e);
	}catch (Exception e) {
		logger.error("",e);
		return Result.error(e.getMessage());

	}  
		return Result.ok();
	}
	*/

	/**
    @ApiOperation( value = "批量修改某些字段",notes="")
    @ApiEntityParams( value = ArchiveUp.class, props={ }, remark = "文章点赞人员列表", paramType = "body" )
	@ApiResponses({
			@ApiResponse(code = 200,response=ArchiveUp.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'},data:数据对象}")
	})
	@RequestMapping(value="/editSomeFields",method=RequestMethod.POST)
	public Result editSomeFields( @ApiIgnore @RequestBody Map<String,Object> archiveUpMap) {
		
		
		try{
			List<Map<String,Object>> pkList= (List<Map<String,Object>>) archiveUpMap.get("pkList");
			if(pkList==null || pkList.size()==0){
				return failed("pkList-0","pkList不能为空");
			}

			Set<String> fields=new HashSet<>();
            fields.add("archiveId");
            fields.add("userid");
			for (String fieldName : archiveUpMap.keySet()) {
				if(fields.contains(fieldName)){
					return failed(fieldName+"-no-edit",fieldName+"不允许修改");
				}
			}
			Set<String> fieldKey=archiveUpMap.keySet().stream().filter(i-> fieldsMap.containsKey(i)).collect(Collectors.toSet());
			fieldKey=fieldKey.stream().filter(i->!StringUtils.isEmpty(archiveUpMap.get(i) )).collect(Collectors.toSet());

			if(fieldKey.size()<=0) {
				return failed("fieldKey-0","没有需要更新的字段");
 			}
			ArchiveUp archiveUp = fromMap(archiveUpMap,ArchiveUp.class);
			List<ArchiveUp> archiveUpsDb=archiveUpService.selectListByIds(pkList);
			if(archiveUpsDb==null ||archiveUpsDb.size()==0){
				return failed("data-0","记录已不存在");
			}
			List<ArchiveUp> can=new ArrayList<>();
			List<ArchiveUp> no=new ArrayList<>();
			User user = LoginUtils.getCurrentUserInfo();
			for (ArchiveUp archiveUpDb : archiveUpsDb) {
				Tips tips2 = new Tips("检查通过"); 
				if(!tips2.isOk()){
				    no.add(archiveUpDb); 
				}else{
					can.add(archiveUpDb);
				}
			}
			if(can.size()>0){
                archiveUpMap.put("pkList",can.stream().map(i->map( "archiveId",i.getArchiveId(),  "userid",i.getUserid())).collect(Collectors.toList()));
			    archiveUpService.editSomeFields(archiveUpMap); 
			}
			List<String> msgs=new ArrayList<>();
			if(can.size()>0){
				msgs.add(String.format("成功更新以下%s条数据",can.size()));
			}
			if(no.size()>0){
				msgs.add(String.format("以下%s个数据无权限更新",no.size()));
			}
			if(can.size()>0){
				return Result.ok(msgs.stream().collect(Collectors.joining()));
			}else {
				return Result.error(msgs.stream().collect(Collectors.joining()));
			}
			//return Result.ok().setData(xmMenu);
		}catch (BizException e) { 
			logger.error("",e);
			return Result.error(e);
		}catch (Exception e) { 
			logger.error("",e);
			return Result.error(e.getMessage());
		}
		return Result.ok();
	}
	*/

	/**
	@ApiOperation( value = "根据主键列表批量删除文章点赞人员列表信息",notes=" ")
	@ApiResponses({
		@ApiResponse(code = 200, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'}")
	}) 
	@RequestMapping(value="/batchDel",method=RequestMethod.POST)
	public Result batchDelArchiveUp(@RequestBody List<ArchiveUp> archiveUps) {
		
        
        try{ 
            if(archiveUps.size()<=0){
                return failed("data-0","请上送待删除数据列表");
            }
             List<ArchiveUp> datasDb=archiveUpService.selectListByIds(archiveUps.stream().map(i->map( "archiveId",i.getArchiveId() ,  "userid",i.getUserid() )).collect(Collectors.toList()));

            List<ArchiveUp> can=new ArrayList<>();
            List<ArchiveUp> no=new ArrayList<>();
            for (ArchiveUp data : datasDb) {
                if(true){
                    can.add(data);
                }else{
                    no.add(data);
                } 
            }
            List<String> msgs=new ArrayList<>();
            if(can.size()>0){
                archiveUpService.batchDelete(can);
                msgs.add(String.format("成功删除%s条数据.",can.size()));
            }
    
            if(no.size()>0){ 
                msgs.add(String.format("以下%s条数据不能删除.【%s】",no.size(),no.stream().map(i-> i.getArchiveId() +" "+ i.getUserid() ).collect(Collectors.joining(","))));
            }
            if(can.size()>0){
                 return Result.ok(msgs.stream().collect(Collectors.joining()));
            }else {
                return Result.error(msgs.stream().collect(Collectors.joining()));
            }
        }catch (BizException e) { 
            tips=e.getTips();
            logger.error("",e);
        }catch (Exception e) {
            return Result.error(e.getMessage());
            logger.error("",e);
        }  
        m.put("tips", tips);
        return m;
	} 
	*/
}
